package com.atguigu.day03;

import com.atguigu.bean.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/7/10
 * 该案例演示了分组聚合
 * 需求：从指定的网络端口中读取水位传感器采集的水位信息，统计相同的传感器的水位最大值
 */
public class Flink13_Agg_MaxMaxBy {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.从指定的网络端口中读取数据   ws1,10,8
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.对流中数据进行类型转换  String->WaterSensor对象
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());

        //TODO 4.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(new KeySelector<WaterSensor, String>() {
            @Override
            public String getKey(WaterSensor ws) throws Exception {
                return ws.getId();
            }
        });

        //TODO 5.统计
        //SingleOutputStreamOperator<WaterSensor> sumDS = keyedDS.max("vc");
        SingleOutputStreamOperator<WaterSensor> sumDS = keyedDS.maxBy("vc");
        //TODO 6.打印输出结果
        sumDS.print();
        //TODO 7.提交作业
        env.execute();
    }
}
